<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Window Management API</h1>
        <p class="text-gray-300 text-lg">
          多屏幕窗口管理，精确控制窗口位置和显示器信息
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 Window Management API。此功能需要 Chrome 100+、Edge 100+ 或其他支持的浏览器。
        </p>
        <p class="text-yellow-400 text-sm mt-2">
          注意：需要 HTTPS 环境和用户授权才能使用此 API。
        </p>
      </div>

      <template v-if="isSupported">
        <!-- 权限请求 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-security text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">权限管理</h2>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <div>
                <h3 class="text-white font-semibold mb-2">Window Placement 权限</h3>
                <p class="text-gray-400 text-sm">
                  需要用户授权才能访问多屏幕信息和精确控制窗口位置
                </p>
              </div>
              <span
                :class="[
                  permissionState === 'granted' ? 'bg-green-600' :
                  permissionState === 'denied' ? 'bg-red-600' :
                  'bg-yellow-600',
                  'px-3 py-1 rounded text-white text-sm'
                ]"
              >
                {{ getPermissionText(permissionState) }}
              </span>
            </div>

            <div class="flex gap-3">
              <button
                @click="requestPermission"
                :disabled="permissionState === 'granted'"
                class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="i-carbon-locked mr-2"></i>
                请求权限
              </button>

              <button
                @click="checkPermission"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
              >
                <i class="i-carbon-renew mr-2"></i>
                检查权限
              </button>
            </div>
          </div>
        </div>

        <!-- 屏幕信息 -->
        <div v-if="permissionState === 'granted'" class="tech-card mb-8">
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center">
              <i class="i-carbon-screen text-3xl text-tech-accent mr-3"></i>
              <h2 class="text-2xl font-semibold text-white">屏幕信息</h2>
            </div>
            <button
              @click="refreshScreens"
              class="text-tech-accent hover:text-tech-accent-light text-sm"
            >
              <i class="i-carbon-renew mr-1"></i>
              刷新
            </button>
          </div>

          <div class="space-y-6">
            <!-- 屏幕概览 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">屏幕概览</h3>
              
              <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <i class="i-carbon-screen text-3xl text-tech-accent mb-2 block"></i>
                  <div class="text-2xl font-bold text-white mb-1">{{ screens.length }}</div>
                  <div class="text-gray-400 text-sm">检测到的屏幕</div>
                </div>

                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <i class="i-carbon-star text-3xl text-yellow-500 mb-2 block"></i>
                  <div class="text-2xl font-bold text-white mb-1">{{ primaryScreenIndex + 1 }}</div>
                  <div class="text-gray-400 text-sm">主屏幕</div>
                </div>

                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <i class="i-carbon-laptop text-3xl text-blue-500 mb-2 block"></i>
                  <div class="text-2xl font-bold text-white mb-1">{{ internalScreens }}</div>
                  <div class="text-gray-400 text-sm">内置屏幕</div>
                </div>

                <div class="bg-gray-900 rounded-lg p-4 text-center">
                  <i class="i-carbon-plug text-3xl text-green-500 mb-2 block"></i>
                  <div class="text-2xl font-bold text-white mb-1">{{ externalScreens }}</div>
                  <div class="text-gray-400 text-sm">外接屏幕</div>
                </div>
              </div>
            </div>

            <!-- 当前窗口信息 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">当前窗口信息</h3>
              
              <div class="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">位置 X</div>
                  <div class="text-white font-semibold">{{ currentWindow.x }} px</div>
                </div>
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">位置 Y</div>
                  <div class="text-white font-semibold">{{ currentWindow.y }} px</div>
                </div>
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">宽度</div>
                  <div class="text-white font-semibold">{{ currentWindow.width }} px</div>
                </div>
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">高度</div>
                  <div class="text-white font-semibold">{{ currentWindow.height }} px</div>
                </div>
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">设备像素比</div>
                  <div class="text-white font-semibold">{{ currentWindow.devicePixelRatio }}</div>
                </div>
                <div class="bg-gray-900 rounded p-3">
                  <div class="text-gray-400">所在屏幕</div>
                  <div class="text-white font-semibold">屏幕 {{ currentScreenIndex + 1 }}</div>
                </div>
              </div>
            </div>

            <!-- 屏幕详细信息 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">所有屏幕详情</h3>

              <div class="space-y-4">
                <div
                  v-for="(screen, index) in screens"
                  :key="index"
                  :class="[
                    screen.isPrimary ? 'border-yellow-500' : 'border-gray-700',
                    'bg-gray-900 rounded-lg p-4 border-2'
                  ]"
                >
                  <div class="flex items-start justify-between mb-3">
                    <div>
                      <h4 class="text-white font-semibold text-lg">
                        屏幕 {{ index + 1 }}
                        <span v-if="screen.isPrimary" class="text-yellow-500 text-sm ml-2">
                          <i class="i-carbon-star"></i> 主屏幕
                        </span>
                        <span v-if="screen.isInternal" class="text-blue-500 text-sm ml-2">
                          <i class="i-carbon-laptop"></i> 内置
                        </span>
                      </h4>
                      <p v-if="screen.label" class="text-gray-400 text-sm mt-1">{{ screen.label }}</p>
                    </div>
                    <button
                      @click="selectScreen(index)"
                      :class="[
                        selectedScreenIndex === index ? 'bg-tech-accent' : 'bg-gray-700 hover:bg-gray-600',
                        'text-white px-3 py-1 rounded text-sm transition-colors'
                      ]"
                    >
                      {{ selectedScreenIndex === index ? '已选择' : '选择' }}
                    </button>
                  </div>

                  <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
                    <div>
                      <div class="text-gray-400">可用区域</div>
                      <div class="text-white">{{ screen.availWidth }} × {{ screen.availHeight }}</div>
                    </div>
                    <div>
                      <div class="text-gray-400">总尺寸</div>
                      <div class="text-white">{{ screen.width }} × {{ screen.height }}</div>
                    </div>
                    <div>
                      <div class="text-gray-400">位置</div>
                      <div class="text-white">{{ screen.left }}, {{ screen.top }}</div>
                    </div>
                    <div>
                      <div class="text-gray-400">可用位置</div>
                      <div class="text-white">{{ screen.availLeft }}, {{ screen.availTop }}</div>
                    </div>
                    <div>
                      <div class="text-gray-400">颜色深度</div>
                      <div class="text-white">{{ screen.colorDepth }} bit</div>
                    </div>
                    <div>
                      <div class="text-gray-400">像素深度</div>
                      <div class="text-white">{{ screen.pixelDepth }} bit</div>
                    </div>
                    <div>
                      <div class="text-gray-400">设备像素比</div>
                      <div class="text-white">{{ screen.devicePixelRatio }}</div>
                    </div>
                    <div>
                      <div class="text-gray-400">方向</div>
                      <div class="text-white">{{ getOrientationText(screen) }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 窗口控制 -->
        <div v-if="permissionState === 'granted'" class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-application text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">窗口控制</h2>
          </div>

          <div class="space-y-6">
            <!-- 新建窗口 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">新建窗口</h3>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-300 mb-2 text-sm">目标屏幕:</label>
                  <select
                    v-model="newWindow.screenIndex"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option
                      v-for="(screen, index) in screens"
                      :key="index"
                      :value="index"
                    >
                      屏幕 {{ index + 1 }}{{ screen.isPrimary ? ' (主屏幕)' : '' }}
                    </option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">窗口类型:</label>
                  <select
                    v-model="newWindow.type"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option value="normal">普通窗口</option>
                    <option value="popup">弹出窗口</option>
                    <option value="fullscreen">全屏窗口</option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">宽度 (px):</label>
                  <input
                    v-model.number="newWindow.width"
                    type="number"
                    min="100"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">高度 (px):</label>
                  <input
                    v-model.number="newWindow.height"
                    type="number"
                    min="100"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">X 位置:</label>
                  <input
                    v-model.number="newWindow.x"
                    type="number"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">Y 位置:</label>
                  <input
                    v-model.number="newWindow.y"
                    type="number"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>
              </div>

              <div class="flex gap-3 flex-wrap">
                <button
                  @click="openNewWindow"
                  class="tech-button"
                >
                  <i class="i-carbon-add mr-2"></i>
                  打开新窗口
                </button>

                <button
                  @click="openWindowOnScreen(selectedScreenIndex)"
                  :disabled="selectedScreenIndex === null"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-screen mr-2"></i>
                  在选中屏幕打开
                </button>

                <button
                  @click="openWindowCentered"
                  class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors"
                >
                  <i class="i-carbon-center-circle mr-2"></i>
                  居中打开
                </button>

                <button
                  @click="openFullscreenWindow"
                  class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors"
                >
                  <i class="i-carbon-maximize mr-2"></i>
                  全屏打开
                </button>
              </div>
            </div>

            <!-- 快速操作 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">快速操作</h3>

              <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                <button
                  @click="spanAllScreens"
                  class="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-4 py-3 rounded-lg transition-colors text-sm"
                >
                  <i class="i-carbon-grid block text-2xl mb-1 mx-auto"></i>
                  跨所有屏幕
                </button>

                <button
                  @click="openOnEachScreen"
                  class="bg-gradient-to-r from-green-600 to-teal-600 hover:from-green-700 hover:to-teal-700 text-white px-4 py-3 rounded-lg transition-colors text-sm"
                >
                  <i class="i-carbon-copy-file block text-2xl mb-1 mx-auto"></i>
                  每屏一个窗口
                </button>

                <button
                  @click="tileWindows"
                  class="bg-gradient-to-r from-orange-600 to-red-600 hover:from-orange-700 hover:to-red-700 text-white px-4 py-3 rounded-lg transition-colors text-sm"
                >
                  <i class="i-carbon-dashboard block text-2xl mb-1 mx-auto"></i>
                  平铺窗口
                </button>

                <button
                  @click="closeAllWindows"
                  :disabled="openedWindows.length === 0"
                  class="bg-gradient-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white px-4 py-3 rounded-lg transition-colors text-sm disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-close block text-2xl mb-1 mx-auto"></i>
                  关闭所有 ({{ openedWindows.length }})
                </button>
              </div>
            </div>

            <!-- 已打开的窗口 -->
            <div v-if="openedWindows.length > 0" class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">已打开的窗口 ({{ openedWindows.length }})</h3>

              <div class="space-y-2">
                <div
                  v-for="(win, index) in openedWindows"
                  :key="index"
                  class="bg-gray-900 rounded p-3 flex items-center justify-between"
                >
                  <div class="text-sm">
                    <span class="text-white font-semibold">窗口 {{ index + 1 }}</span>
                    <span class="text-gray-400 ml-2">{{ win.url }}</span>
                  </div>
                  <div class="flex gap-2">
                    <button
                      @click="focusWindow(win.window)"
                      class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-xs transition-colors"
                    >
                      <i class="i-carbon-focus mr-1"></i>
                      聚焦
                    </button>
                    <button
                      @click="closeWindow(index)"
                      class="bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-xs transition-colors"
                    >
                      <i class="i-carbon-close mr-1"></i>
                      关闭
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 屏幕变化监听 -->
        <div v-if="permissionState === 'granted'" class="tech-card mb-8">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-semibold text-white">屏幕变化监听</h2>
            <button
              @click="clearEvents"
              class="text-red-400 hover:text-red-300 text-sm"
            >
              <i class="i-carbon-clean mr-1"></i>
              清空事件
            </button>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div v-if="screenEvents.length === 0" class="text-center py-8 text-gray-400">
              暂无屏幕变化事件。尝试连接/断开外接显示器，或调整窗口大小。
            </div>

            <div v-else class="space-y-2 max-h-96 overflow-y-auto">
              <div
                v-for="(event, index) in screenEvents.slice().reverse()"
                :key="index"
                class="bg-gray-900 rounded p-3 border-l-4 border-blue-500"
              >
                <div class="flex justify-between items-start mb-1">
                  <span class="text-blue-400 font-semibold">{{ event.type }}</span>
                  <span class="text-gray-500 text-xs">{{ event.timestamp }}</span>
                </div>
                <div class="text-gray-300 text-sm">{{ event.message }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 100+, Edge 100+</p>
            <p class="text-sm text-yellow-400 mt-1">注意：需要 HTTPS 环境和用户授权</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">window.getScreenDetails()</code> - 获取所有屏幕信息</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">window.screen</code> - 当前屏幕信息</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">window.open()</code> - 打开新窗口（支持多屏幕定位）</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">ScreenDetails</code> - 屏幕详情接口</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">ScreenDetailed</code> - 详细屏幕信息</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">基本用法</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// 请求权限</span>
<span class="text-blue-400">const</span> permission = <span class="text-blue-400">await</span> navigator.permissions.query({
  name: <span class="text-green-400">'window-placement'</span>
});

<span class="text-gray-500">// 获取所有屏幕</span>
<span class="text-blue-400">const</span> screenDetails = <span class="text-blue-400">await</span> window.getScreenDetails();
console.log(screenDetails.screens); <span class="text-gray-500">// 所有屏幕数组</span>
console.log(screenDetails.currentScreen); <span class="text-gray-500">// 当前屏幕</span>

<span class="text-gray-500">// 在指定屏幕打开窗口</span>
<span class="text-blue-400">const</span> screen = screenDetails.screens[<span class="text-orange-400">1</span>]; <span class="text-gray-500">// 第二个屏幕</span>
<span class="text-blue-400">const</span> left = screen.availLeft + <span class="text-orange-400">100</span>;
<span class="text-blue-400">const</span> top = screen.availTop + <span class="text-orange-400">100</span>;
window.open(<span class="text-green-400">'page.html'</span>, <span class="text-green-400">'_blank'</span>, 
  <span class="text-green-400">`left=<span class="text-orange-400">${left}</span>,top=<span class="text-orange-400">${top}</span>,width=800,height=600`</span>);</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">屏幕信息</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><strong>availWidth/availHeight:</strong> 可用区域尺寸（排除任务栏等）</li>
              <li><strong>width/height:</strong> 屏幕总尺寸</li>
              <li><strong>left/top:</strong> 屏幕在虚拟屏幕空间的位置</li>
              <li><strong>availLeft/availTop:</strong> 可用区域的位置</li>
              <li><strong>isPrimary:</strong> 是否为主屏幕</li>
              <li><strong>isInternal:</strong> 是否为内置屏幕</li>
              <li><strong>devicePixelRatio:</strong> 设备像素比</li>
              <li><strong>colorDepth/pixelDepth:</strong> 颜色深度</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>多屏幕展示应用（演示软件）</li>
              <li>金融交易平台（多屏监控）</li>
              <li>视频会议（控制台+演示窗口）</li>
              <li>设计工具（工作区分离）</li>
              <li>游戏多屏扩展</li>
              <li>数据仪表板（跨屏显示）</li>
              <li>远程桌面应用</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">事件监听</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// 监听屏幕变化</span>
screenDetails.addEventListener(<span class="text-green-400">'screenschange'</span>, () => {
  console.log(<span class="text-green-400">'屏幕配置已改变'</span>);
  <span class="text-gray-500">// 更新屏幕列表</span>
});

<span class="text-gray-500">// 监听当前屏幕变化</span>
screenDetails.addEventListener(<span class="text-green-400">'currentscreenchange'</span>, () => {
  console.log(<span class="text-green-400">'当前窗口移动到了另一个屏幕'</span>);
});</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>始终检查 API 可用性</li>
              <li>优雅处理权限被拒绝的情况</li>
              <li>监听屏幕配置变化并适应</li>
              <li>考虑单屏幕用户的体验</li>
              <li>保存用户的窗口布局偏好</li>
              <li>确保窗口不会超出屏幕边界</li>
              <li>妥善管理打开的窗口引用</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">安全性</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>需要用户明确授权</li>
              <li>需要 HTTPS 环境（或 localhost）</li>
              <li>权限可被用户随时撤销</li>
              <li>弹出窗口可能被浏览器拦截</li>
              <li>跨域窗口通信受限</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 类型定义
interface ScreenEvent {
  type: string
  message: string
  timestamp: string
}

interface NewWindowConfig {
  screenIndex: number
  type: 'normal' | 'popup' | 'fullscreen'
  width: number
  height: number
  x: number
  y: number
}

interface OpenedWindow {
  window: Window | null
  url: string
}

// 响应式状态
const isSupported = ref(false)
const permissionState = ref<PermissionState>('prompt')
const screens = ref<ScreenDetailed[]>([])
const currentScreen = ref<ScreenDetailed | null>(null)
const selectedScreenIndex = ref<number | null>(null)
const screenEvents = ref<ScreenEvent[]>([])
const openedWindows = ref<OpenedWindow[]>([])

// 当前窗口信息
const currentWindow = ref({
  x: window.screenX,
  y: window.screenY,
  width: window.innerWidth,
  height: window.innerHeight,
  devicePixelRatio: window.devicePixelRatio
})

// 新窗口配置
const newWindow = ref<NewWindowConfig>({
  screenIndex: 0,
  type: 'normal',
  width: 800,
  height: 600,
  x: 100,
  y: 100
})

// ScreenDetails 实例
let screenDetails: any = null

// 计算属性
const primaryScreenIndex = computed(() => {
  return screens.value.findIndex(s => s.isPrimary)
})

const currentScreenIndex = computed(() => {
  return screens.value.findIndex(s => s === currentScreen.value)
})

const internalScreens = computed(() => {
  return screens.value.filter(s => s.isInternal).length
})

const externalScreens = computed(() => {
  return screens.value.filter(s => !s.isInternal).length
})

// 初始化
onMounted(async () => {
  isSupported.value = 'getScreenDetails' in window
  
  if (isSupported.value) {
    await checkPermission()
    
    // 监听窗口移动和调整大小
    window.addEventListener('resize', updateCurrentWindow)
    window.addEventListener('move', updateCurrentWindow)
  }
})

// 清理
onUnmounted(() => {
  if (isSupported.value) {
    window.removeEventListener('resize', updateCurrentWindow)
    window.removeEventListener('move', updateCurrentWindow)
  }
  
  // 关闭所有打开的窗口
  closeAllWindows()
})

// 检查权限
const checkPermission = async () => {
  try {
    const result = await navigator.permissions.query({ name: 'window-placement' as PermissionName })
    permissionState.value = result.state
    
    result.addEventListener('change', () => {
      permissionState.value = result.state
      addEvent('权限变化', `Window Placement 权限状态: ${getPermissionText(result.state)}`)
    })
    
    if (permissionState.value === 'granted') {
      await loadScreenDetails()
    }
  } catch (error) {
    console.error('检查权限失败:', error)
  }
}

// 请求权限
const requestPermission = async () => {
  try {
    await loadScreenDetails()
    await checkPermission()
  } catch (error) {
    console.error('请求权限失败:', error)
    alert('请求权限失败，请确保使用 HTTPS 环境')
  }
}

// 加载屏幕详情
const loadScreenDetails = async () => {
  try {
    screenDetails = await (window as any).getScreenDetails()
    screens.value = screenDetails.screens
    currentScreen.value = screenDetails.currentScreen
    
    // 监听屏幕变化
    screenDetails.addEventListener('screenschange', handleScreensChange)
    screenDetails.addEventListener('currentscreenchange', handleCurrentScreenChange)
    
    addEvent('屏幕信息', `检测到 ${screens.value.length} 个屏幕`)
  } catch (error) {
    console.error('加载屏幕详情失败:', error)
    throw error
  }
}

// 刷新屏幕信息
const refreshScreens = async () => {
  await loadScreenDetails()
  addEvent('刷新', '屏幕信息已刷新')
}

// 更新当前窗口信息
const updateCurrentWindow = () => {
  currentWindow.value = {
    x: window.screenX,
    y: window.screenY,
    width: window.innerWidth,
    height: window.innerHeight,
    devicePixelRatio: window.devicePixelRatio
  }
}

// 选择屏幕
const selectScreen = (index: number) => {
  selectedScreenIndex.value = index
  const screen = screens.value[index]
  
  // 更新新窗口配置
  newWindow.value.screenIndex = index
  newWindow.value.x = screen.availLeft + 100
  newWindow.value.y = screen.availTop + 100
}

// 打开新窗口
const openNewWindow = () => {
  const screen = screens.value[newWindow.value.screenIndex]
  
  const features: string[] = [
    `left=${newWindow.value.x}`,
    `top=${newWindow.value.y}`,
    `width=${newWindow.value.width}`,
    `height=${newWindow.value.height}`
  ]
  
  if (newWindow.value.type === 'popup') {
    features.push('popup=yes')
  }
  
  const win = window.open('about:blank', '_blank', features.join(','))
  
  if (win) {
    // 写入内容
    win.document.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <title>新窗口 - 屏幕 ${newWindow.value.screenIndex + 1}</title>
        <style>
          body {
            margin: 0;
            padding: 20px;
            font-family: system-ui;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
          }
          h1 { font-size: 2em; margin-bottom: 10px; }
          p { font-size: 1.2em; opacity: 0.9; }
          .info { background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; margin-top: 20px; }
        </style>
      </head>
      <body>
        <h1>🖥️ 窗口已打开</h1>
        <p>这个窗口在屏幕 ${newWindow.value.screenIndex + 1} 上</p>
        <div class="info">
          <p>位置: (${newWindow.value.x}, ${newWindow.value.y})</p>
          <p>尺寸: ${newWindow.value.width} × ${newWindow.value.height}</p>
          <p>屏幕: ${screen.width} × ${screen.height}</p>
        </div>
      </body>
      </html>
    `)
    
    openedWindows.value.push({
      window: win,
      url: `屏幕 ${newWindow.value.screenIndex + 1}`
    })
    
    addEvent('打开窗口', `在屏幕 ${newWindow.value.screenIndex + 1} 打开新窗口`)
  } else {
    alert('窗口被浏览器拦截，请允许弹出窗口')
  }
}

// 在指定屏幕打开窗口
const openWindowOnScreen = (screenIndex: number | null) => {
  if (screenIndex === null) return
  
  newWindow.value.screenIndex = screenIndex
  openNewWindow()
}

// 居中打开窗口
const openWindowCentered = () => {
  const screen = screens.value[newWindow.value.screenIndex]
  
  newWindow.value.x = screen.availLeft + (screen.availWidth - newWindow.value.width) / 2
  newWindow.value.y = screen.availTop + (screen.availHeight - newWindow.value.height) / 2
  
  openNewWindow()
}

// 全屏打开窗口
const openFullscreenWindow = () => {
  const screen = screens.value[newWindow.value.screenIndex]
  
  newWindow.value.x = screen.availLeft
  newWindow.value.y = screen.availTop
  newWindow.value.width = screen.availWidth
  newWindow.value.height = screen.availHeight
  
  openNewWindow()
}

// 跨所有屏幕
const spanAllScreens = () => {
  if (screens.value.length === 0) return
  
  const leftmost = Math.min(...screens.value.map(s => s.left))
  const topmost = Math.min(...screens.value.map(s => s.top))
  const rightmost = Math.max(...screens.value.map(s => s.left + s.width))
  const bottommost = Math.max(...screens.value.map(s => s.top + s.height))
  
  newWindow.value.x = leftmost
  newWindow.value.y = topmost
  newWindow.value.width = rightmost - leftmost
  newWindow.value.height = bottommost - topmost
  
  openNewWindow()
}

// 在每个屏幕打开一个窗口
const openOnEachScreen = () => {
  screens.value.forEach((screen, index) => {
    setTimeout(() => {
      newWindow.value.screenIndex = index
      newWindow.value.x = screen.availLeft + 50
      newWindow.value.y = screen.availTop + 50
      newWindow.value.width = 600
      newWindow.value.height = 400
      openNewWindow()
    }, index * 100)
  })
}

// 平铺窗口
const tileWindows = () => {
  const screen = screens.value[newWindow.value.screenIndex]
  const count = 4
  const cols = 2
  const rows = Math.ceil(count / cols)
  
  const width = Math.floor(screen.availWidth / cols)
  const height = Math.floor(screen.availHeight / rows)
  
  for (let i = 0; i < count; i++) {
    const col = i % cols
    const row = Math.floor(i / cols)
    
    setTimeout(() => {
      newWindow.value.x = screen.availLeft + col * width
      newWindow.value.y = screen.availTop + row * height
      newWindow.value.width = width
      newWindow.value.height = height
      openNewWindow()
    }, i * 100)
  }
}

// 聚焦窗口
const focusWindow = (win: Window | null) => {
  if (win && !win.closed) {
    win.focus()
  }
}

// 关闭窗口
const closeWindow = (index: number) => {
  const win = openedWindows.value[index]
  if (win.window && !win.window.closed) {
    win.window.close()
  }
  openedWindows.value.splice(index, 1)
}

// 关闭所有窗口
const closeAllWindows = () => {
  openedWindows.value.forEach(win => {
    if (win.window && !win.window.closed) {
      win.window.close()
    }
  })
  openedWindows.value = []
  addEvent('关闭窗口', '已关闭所有打开的窗口')
}

// 处理屏幕变化
const handleScreensChange = () => {
  screens.value = screenDetails.screens
  addEvent('屏幕变化', `屏幕配置已改变，当前有 ${screens.value.length} 个屏幕`)
}

// 处理当前屏幕变化
const handleCurrentScreenChange = () => {
  currentScreen.value = screenDetails.currentScreen
  addEvent('当前屏幕变化', '窗口移动到了另一个屏幕')
}

// 添加事件
const addEvent = (type: string, message: string) => {
  screenEvents.value.push({
    type,
    message,
    timestamp: new Date().toLocaleTimeString('zh-CN')
  })
}

// 清空事件
const clearEvents = () => {
  screenEvents.value = []
}

// 获取权限文本
const getPermissionText = (state: PermissionState): string => {
  const states: Record<PermissionState, string> = {
    granted: '已授权',
    denied: '已拒绝',
    prompt: '待请求'
  }
  return states[state] || state
}

// 获取方向文本
const getOrientationText = (screen: ScreenDetailed): string => {
  return screen.width > screen.height ? '横向' : '纵向'
}
</script>

<style scoped>
/* 自定义样式 */
</style>

